<template>
  <div>
    <!-- 订单信息 -->
    <template v-if="slotName === 'orderSlot'">
      <el-space size="small" direction="vertical" alignment="normal">
        <template v-if="row.productCollection && row.productCollection[0]">
          <div style="font-weight: bold" class="productName">
            {{ getStr(row.productName) }}
            *
            {{ row.productCollection[0].totalUnitNum || '--' }}
          </div>
          <div>
            <el-space>
              <div>
                订单金额：
                <el-tag type="info"> ￥{{ row.productCollection[0].orderPrice }} </el-tag>
              </div>
              <div>
                实付：
                <el-tag type="primary"> ￥{{ row.productCollection[0].actualPrice }} </el-tag>
              </div>
            </el-space>
            <div class="mt-10" style="cursor: pointer" @click="copy(row.orderNo)">
              订单编号：{{ row.orderNo }}
            </div>
            <div class="mt-10" style="cursor: pointer" @click="copy(row.externalOrderId)">
              百度编号：{{ row.externalOrderId }}
            </div>
          </div>
        </template>
      </el-space>
    </template>

    <!-- 订单类型 -->
    <template v-else-if="slotName === 'orderTypeSlot'">
      <el-space v-if="!isChild" size="small" direction="vertical" alignment="normal">
        <!-- 是否是平台转单 -->
        <template v-if="row.transferOrderAmount">
          <el-tag effect="dark" type="success"> 追加订单 </el-tag>
        </template>

        <!-- isMultiPackage == 1 多包裹订单 -->
        <template v-else-if="row.isMultiPackage">
          <el-tag effect="dark" type="primary"> 多包裹 </el-tag>
        </template>
        <!-- isReplenishOrder == 1 是否补单 -->
        <template v-else-if="row.isReplenishOrder">
          <el-tag effect="dark" type="success"> 补发订单 </el-tag>
        </template>
        <!-- else 普通复购订单  -->
        <template v-else>
          <div v-if="row.isDelayedDelivery">
            <el-tag type="danger" effect="dark"> 延期发货 </el-tag>
          </div>
          <el-tag v-else effect="dark" type="info"> 复购订单 </el-tag>
        </template>
      </el-space>
      <el-space v-else>
        <!-- 子母单 -->
        <el-tag type="primary"> 子包裹 </el-tag>
      </el-space>
    </template>

    <!-- 平台订单 客户信息 -->
    <template v-else-if="slotName === 'logisticsSlot'">
      <el-space size="small" direction="vertical" alignment="normal">
        <div style="cursor: pointer">
          <el-space size="small" alignment="normal">
            <span @click="copy(row.receiverName)">{{ row.receiverName }}</span>
            <span @click="copy(row.receiverPhone)">{{ row.receiverPhone || '--' }}</span>
          </el-space>
          <div @click="copy(row.receiverAddress)">{{ row.receiverAddress }}</div>
        </div>
        <div class="payCount">
          <el-space>
            <el-tag
              @click="$emit('payHistory', row)"
              color="#ffff00"
              style="color: #ef5c5c; cursor: pointer"
              plain
              v-if="row.orderCount > 1"
            >
              第{{ row.orderCount || 1 }}次购买
            </el-tag>
            <!-- 剩余时间 根据当前时间 - usageEndTime  -->
            <div v-if="remainingTime.text" class="remaining-time">
              <el-tag :type="remainingTime.color" effect="dark">{{ remainingTime.text }}</el-tag>
            </div>
          </el-space>
        </div>
      </el-space>
    </template>

    <!-- 业务员 -->
    <template v-else-if="slotName === 'salesmanSlot'">
      <div v-if="!isChild">
        <template v-if="row.salesmanId">
          <el-space size="small" direction="vertical" alignment="normal">
            <div>业务员：{{ row.salesmanName || '--' }}</div>
            <div>属部门：{{ row.salesmanDept || '--' }}</div>
          </el-space>
        </template>
        <template v-else>
          <el-tag type="danger">待分配</el-tag>
        </template>
      </div>
    </template>

    <!-- 物流信息 -->
    <template v-else-if="slotName === 'logisticsStatusSlot'">
      <el-space size="small" direction="vertical" alignment="normal" style="width: 100%">
        <template v-if="row.isMultiPackage && !isChild">
          <div :style="`color: ${orderStatus.color}`">
            {{ orderStatus.text }}
          </div>

          <template v-if="row.logisticsNo">
            <div>
              <el-tag type="success">{{ row.logisticsNo || '--' }}</el-tag>
            </div>
            <div>
              <LogisticsTextCollapse
                :text="row.logisticsProgress"
                @tag-click="handleViewLogistics"
              />
            </div>
          </template>
          <el-tag type="warning" effect="dark"> {{ row.childrens.length }} 个包裹 </el-tag>
        </template>

        <template v-else>
          <!-- 快递发货状态 子订单没有单独的快单号 不看子订单状态 -->
          <div v-if="!isChild" :style="`color: ${orderStatus.color}`">
            {{ orderStatus.text }}
          </div>
          <!-- 如果已经有了快递单号 -->
          <template v-if="row.logisticsNo">
            <div>
              <el-tag type="success">{{ row.logisticsNo || '--' }}</el-tag>
            </div>
            <LogisticsTextCollapse :text="row.logisticsProgress" @tag-click="handleViewLogistics" />
          </template>
        </template>
      </el-space>
    </template>

    <!-- 下单签收时间 -->
    <template v-else-if="slotName === 'orderTimerSlot'">
      <el-space v-if="!isChild" size="small" direction="vertical" alignment="normal">
        <div>下单时间：{{ row.orderTime }}</div>
        <div v-if="row.logisticsSignTime">签收时间：{{ row.logisticsSignTime }}</div>
        <div v-if="row.platform">
          <el-tooltip
            class="box-item"
            effect="dark"
            :content="platformStrDetails(row.platform)"
            placement="top-start"
          >
            <el-space>
              {{ platformStr(row.platform) }}
              <el-tag v-if="row.channelType" type="success" effect="light">
                {{ orderFrom(row.channelType) }}</el-tag
              >
            </el-space>
          </el-tooltip>
        </div>
      </el-space>
    </template>

    <!-- 类别 -->
    <template v-else-if="slotName === 'categorySlot'">
      <EditableMultiSelect
        v-if="!isChild"
        v-model="category"
        placeholder="请选择"
        :options="customStore.customerTypeOptions"
        @change="categoryChange"
      />
    </template>

    <!-- 微信是否填写 -->
    <template v-else-if="slotName === 'wechatSlot'">
      <EditableSelect
        v-if="!isChild"
        v-model="isAddWechat"
        placeholder="请选择"
        :options="customStore.addWeChatOptions"
        @change="wechatChange"
      />
    </template>

    <!-- 备注 -->
    <template v-else-if="slotName === 'remarkSlot'">
      <div class="remarkBox" direction="vertical" v-if="!isChild">
        <!-- 客服备注 -->
        <TextCollapse
          v-if="row.followRemark1"
          :text="row.followRemark1"
          type="客服备注"
          @tag-click="$emit('showCustomerFollowUp', row, 1)"
        />
        <div v-else class="detail service" @click="$emit('showCustomerFollowUp', row, 1)">
          客服备注
        </div>
        <!-- 销售备注 -->
        <TextCollapse
          class="mt-5"
          v-if="row.followRemark2"
          :text="row.followRemark2"
          type="销售备注"
          @tag-click="$emit('showCustomerFollowUp', row, 2)"
        />
        <div v-else class="detail sale" @click="$emit('showCustomerFollowUp', row, 2)">
          销售备注
        </div>
      </div>
    </template>

    <!-- 复购订单信息 -->
    <template v-else-if="slotName === 'repeatOrderSlot'">
      <el-space v-if="!isChild" size="small" direction="vertical" alignment="normal">
        <div style="cursor: pointer" @click="copy(row.orderNo)">订单编号：{{ row.orderNo }}</div>
        <div>
          最近订单：<el-tag type="success">
            {{ row.recentAmount ? '￥' + row.recentAmount : '--' }}
          </el-tag>
        </div>
      </el-space>
      <!-- 子包裹只展示订单编号 -->
      <el-space v-else>
        <div style="cursor: pointer" @click="copy(row.orderNo)">订单编号：{{ row.orderNo }}</div>
      </el-space>
    </template>

    <!-- 复购订单收货人 -->
    <template v-else-if="slotName === 'repeatLogisticsSlot'">
      <!-- 多包裹订单 -->
      <el-space v-if="!isChild" size="small" direction="vertical" alignment="normal">
        <div style="cursor: pointer">
          <el-space size="small" alignment="normal">
            <span @click="copy(row.receiverName)">{{ row.receiverName }}</span>
            <span @click="copy(row.receiverPhone)">{{ row.receiverPhone || '--' }}</span>
          </el-space>
          <div @click="copy(row.receiverAddress)">{{ row.receiverAddress }}</div>
        </div>
        <!-- 第几次下单 -->
        <div class="payCount">
          <el-tag
            @click="$emit('payHistory', row)"
            color="#ffff00"
            style="color: #ef5c5c; cursor: pointer"
            plain
          >
            平台下单{{ row.orderCount || 0 }}次 &nbsp; 复购下单{{ row.repOrderCount || 0 }}次
          </el-tag>
        </div>
      </el-space>
    </template>

    <!-- 复购商品数量 -->
    <template v-else-if="slotName === 'repeatDosageSlot'">
      <div class="dosage-info">
        <div class="dosage-header" v-for="types in goods" :key="types.num">
          {{ types.typeValue }}
          <span>{{ types.typeValue ? '：' : '' }}{{ types.num }}</span>
        </div>
      </div>
    </template>

    <!-- 订单金额 -->
    <template v-else-if="slotName === 'repeatOrderAmountSlot'">
      <div class="order-amount">
        <div class="order-amount-header">
          <span>总金额：</span>
          <span>{{ row.orderAmount || 0 }}</span>
        </div>
        <div class="order-amount-header">
          <span>已收金额：</span>
          <span>{{ row.paidAmount || 0 }}</span>
        </div>
        <div class="order-amount-header">
          <span>代收金额：</span>
          <span>{{ row.unpaidAmount || 0 }}</span>
        </div>
      </div>
    </template>

    <!-- 客户信息 客户数据 -->
    <template v-else-if="slotName === 'customerSlot'">
      <el-space size="small" direction="vertical" alignment="normal">
        <div style="cursor: pointer">
          <el-space size="small" alignment="normal">
            <span @click="copy(row.customerName)">{{ row.customerName }}</span>
            <span @click="copy(row.customerPhone)">{{ row.customerPhone || '--' }}</span>
          </el-space>
          <div @click="copy(row.contactAddress)">{{ row.contactAddress }}</div>
        </div>
        <!-- 第几次下单 -->
        <div class="payCount">
          <el-space>
            <el-tag
              @click="$emit('payHistory', row)"
              color="#ffff00"
              style="color: #ef5c5c; cursor: pointer"
              plain
              v-if="row.sysCount || row.reCount"
            >
              {{ row.sysCount ? '平台下单' + row.sysCount + '次' : '' }}
              {{ row.reCount ? '复购下单' + row.reCount + '次' : '' }}
            </el-tag>

            <!-- 剩余时间 根据当前时间 - usageEndTime  -->
            <div v-if="remainingTime.text" class="remaining-time">
              <el-tag :type="remainingTime.color">{{ remainingTime.text }}</el-tag>
            </div>
          </el-space>
        </div>
      </el-space>
    </template>

    <!-- 售后---------------------------- -->

    <!-- 售后状态 -->
    <template v-else-if="slotName === 'afterSaleStatusSlot'">
      <div>{{ afterSaleStatus }}</div>
    </template>

    <!-- 售后物流状态 -->
    <template v-else-if="slotName === 'afterLogisticsStatusSlot'">
      <div>{{ afterLogisticsStatus }}</div>
    </template>

    <!-- 售后类型 -->
    <template v-else-if="slotName === 'saleTypeSlot'">
      <div>{{ afterSaleType }}</div>
    </template>
  </div>
</template>

<script setup lang="ts">
import {
  getStr,
  orderFrom,
  orderStatusStr,
  platformStr,
  platformStrDetails
} from '../../utils/order';
import { useClipboard } from '../../hooks/useClipboard';
import { computed, inject, Ref, ref, watch } from 'vue';
import { updateCustomer } from '../../api/customers';
import { useCustomStore } from '../../store/modules/custom';
import { dayjs, ElMessage } from 'element-plus';

const { copy } = useClipboard();
// 获取客户类别和是否添加微信
const customStore = useCustomStore();

// 是否添加微信
const isAddWechat = ref();
// 类别
const category = ref();

const props = defineProps<{
  row: any;
  slotName: string; // 用来判断当前是哪个slot
  goodsTypes: any[];
}>();

// 计算售后状态
const afterSaleStatus = computed(() => {
  const afterSaleStatus: any = customStore.afterSaleStatus.find(
    (item: any) => item.value == props.row.status
  );
  return afterSaleStatus?.label || '';
});

// 计算剩余时间  剩余时间 根据当前时间 - usageEndTime  单位：天
const remainingTime = computed(() => {
  const usageEndTime = props.row.usageEndTime;
  if (!usageEndTime) return '';

  const now = dayjs();
  const end = dayjs(usageEndTime);

  const diffMs = end.valueOf() - now.valueOf();
  const oneDay = 24 * 60 * 60 * 1000;

  let diffDays = 0;

  if (diffMs > 0) {
    // 剩余时间：不满一天算 1 天，其它向上取整
    diffDays = diffMs < oneDay ? 1 : Math.ceil(diffMs / oneDay);
  } else {
    // 已过期：向下取整（过期 1.x 天 = 1 天）
    diffDays = Math.floor(diffMs / oneDay);
  }

  const absDays = Math.abs(diffDays);

  let text = '';
  let color: 'success' | 'warning' | 'danger' = 'success';

  if (diffDays < 0) {
    text = `已${absDays}天`;
    color = 'danger';
  } else if (diffDays > 7) {
    text = `还有${diffDays}天用完`;
    color = 'success';
  } else {
    text = `${diffDays}天后用完`;
    color = 'warning';
  }

  return { text, color };
});

// 售后物流类型
const afterLogisticsStatus = computed(() => {
  const afterLogisticsStatus: any = customStore.logisticsStatus.find(
    (item: any) => item.value == props.row.sendStatus
  );
  return afterLogisticsStatus?.label || '';
});

// 计算售后类型 售后类型（1仅客诉 2仅退款 3退货退款）
const afterSaleType = computed(() => {
  const saleType: any = customStore.saleReturnType.find(
    (item: any) => item.value == props.row.type
  );
  return saleType?.label || '';
});

// 根据row 来判断当前是复购订单还是普通订单
const orderStatus = computed(() => {
  const orderDetails = orderStatusStr(props.row.orderStatus);
  if (orderDetails) {
    return orderDetails;
  }
  return {
    text: '',
    color: ''
  };
});

// 计算是否是二级组件 chidlrens
const isChild = computed(() => {
  return props.row.isChildren;
});

// 注入全局弹窗引用
const logisticsDialog = inject<Ref<{ show: (id: string) => void } | null>>(
  'globalLogisticsDialog',
  ref(null)
);

// 查看物流轨迹
const handleViewLogistics = () => {
  logisticsDialog.value?.show(props.row);
};

// 修改订单的客户类别
const categoryChange = (newValue: any) => {
  updateCustomer({
    customerId: props.row.customerId,
    category: newValue.join(',')
  }).then((res: any) => {
    if (res.code == 200) {
      ElMessage.success('修改成功');
    }
  });
};

// 修改订单得客户是否添加微信
const wechatChange = (newValue: any) => {
  updateCustomer({
    customerId: props.row.customerId,
    isAddWechat: newValue
  }).then((res: any) => {
    if (res.code == 200) {
      ElMessage.success('修改成功');
    }
  });
};

// 根据商品的type 计算对应的商品数量
const goods = computed(() => {
  const goods = props.row.productCollection;
  try {
    return goods?.map((g: any) => {
      g.typeValue = props.goodsTypes.find((t) => t.value == g.usageType)?.label;
      return g;
    });
  } catch (e) {
    console.log('e ==> ', e);
    return [];
  }
});

watch(
  () => props.row,
  (newRow) => {
    // 同步类别
    if (newRow.category) {
      category.value = (newRow.category || '').split(',');
    }
    // 是否添加微信
    isAddWechat.value = String(newRow.isAddWechat);
  },
  {
    immediate: true,
    deep: true
  }
);
</script>

<style lang="scss" scoped>
// 备注
.remarkBox {
  .newReamark {
    text-wrap: wrap;
    text-align: center;
    padding: 0 10px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .detail {
    width: 76px;
    border-radius: 4px;
    font-family: Source Han Sans CN;
    font-weight: 400;
    font-size: 13px;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
  }

  // 客服
  .service {
    color: #71c73f;
    background: #f6ffe8;
    border: 1px solid #85d756;
  }

  // 销售
  .sale {
    border: 1px solid #1890ff;
    background: #ecf5ff;
    color: #1890ff;
    margin-top: 10px;
  }
}
</style>
